import React, { Component } from 'react';
import {getCode,login} from '../api/user';

class Login extends Component {
    state = {
        username:'',
        password:'',
        code:''
    }
    render() {
        let {username,password,code} = this.state;
        return (
            <div>
                用户名：<input type="text" value={username} name="username" onChange={this.change}></input>
                密码:<input type="text" value={password} name="password"  onChange={this.change}></input>
                验证码:<input type="text" value={code} name="code" onChange={this.change}></input> <button onClick={this.getCode}>获取验证码</button>
                <button onClick={this.login}>登录</button>
            </div>
        );
    }

    //获取验证码
    getCode = () => {
        getCode().then(res => {
            if(res.data.code === 1){
                console.log(res.data.data);
            }
        })
    }

    //change
    change = (e) => {
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    //登录
    login = () => {
        let {username,password,code} = this.state;

        if(username && password && code){
            login(this.state).then(res => {
                if(res.data.code === 1){
                    //1.把token存储到本地  2.用户名，身份（普通，会员） 存在本地   3.跳路由
                    localStorage.setItem("token",res.data.token);
                    localStorage.setItem('role_name',res.data.role_name);
                    localStorage.setItem('username',username);
                    this.props.history.push('/main');  //主页面
                }
            })
        }else{
            console.log("参数有误")
        }
    }


}

export default Login;